const api = require("../../../../../utils/cloudAPIUtils");
const utils = require("../../../../../utils/utils");
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        info:{},
        place:{},
        money:'',
        dayMoney:'',
        todayStr:'',
        leaseDate:null,         //日期类型
        revertDateStr:'',
        isAgreement:true,
        formData:{
            leaseStartDate:'',
            leaseDay:1,
            batteryType:null,
            leaseType:2,                    //2:预约到店租借,3:同城快递租借
            appointmentTime:'10:00',
            payType:3,
            appId:wx.getAccountInfoSync().miniProgram.appId
        },
        agreementInfo:{
            title:'用户协议',
            content:'暂无协议内容'
        }
    },

    _buildDate:function(){
        let today = new Date();
        let revertDate = utils.addDay(today,1);
        let formData = this.data.formData;
        formData.leaseStartDate = utils.dateFormat(today);
        this.setData({
            todayStr:utils.dateFormat(today),
            leaseDate:today,
            revertDateStr:utils.dateFormat(revertDate),
            formData:formData
        })
    },

    _loadAgreementInfo:function(type){
        api.post(api.url.agreement,{
            code:type
        },res=>{
            console.log(res)
            if(res.data.code==200){
                this.setData({
                    modalName:'agreement',
                    agreementInfo:res.data.body
                })
            }else if(res.data.msg){
                wx.showModal({
                    content: res.data.msg,
                    showCancel:false
                })
            }else{
                wx.showToast({
                  title: '获取数据失败',
                  icon:'error'
                })
            }
        })
    },

    _loadPriceInfo:function(){
        const _self = this;
        api.post(api.url.bxscnBatteryPrice,{
            placeId:this.data.place.placeId,
            batteryType:this.data.formData.batteryType,
            leaseDay:this.data.formData.leaseDay
        },res=>{
            console.log(res)
            if(res.data.code==200){
                let info = _self.data.info;
                info.depositMoney = res.data.body.depositMoney;
                _self.setData({
                    dayMoney:res.data.body.dayMoney,
                    money:res.data.body.money,
                    info:info
                })
            }else if(res.data.msg){
                wx.showModal({
                    content: res.data.msg,
                    showCancel:false
                })
            }else{
                wx.showToast({
                    title: '计算费用失败',
                    icon:'error'
                })
            }
        })
    },

    bindHideModal:function(){
        this.setData({
            modalName:null
        })
    },

    btnChangeAgreement(){
        this.setData({
            isAgreement:!this.data.isAgreement
        })
    },

    btnPickerChange:function(e){
        let key = e.currentTarget.dataset.key;
        let formData = this.data.formData;
        if('leaseStartDate' == key){
            let date = new Date(e.detail.value);
            //计算与今天的间隔，不能超过5天
            let day = utils.diffDay(new Date(),date);
            if(day > 5){
                wx.showModal({
                  title: '温馨提示',
                  content: '起租日请选择距离今天五天以内',
                  showCancel:false
                })
                return;
            }

            console.log(date);
            formData.leaseStartDate = utils.dateFormat(date);
            let revertDate = utils.addDay(date,formData.leaseDay);
            this.setData({
                leaseDate:date,
                revertDateStr:utils.dateFormat(revertDate),
                formData:formData
            })
        }else if('revertDate' == key){
            let date = new Date(e.detail.value);
            console.log('startdate = ' + utils.dateFormat(this.data.leaseDate));
            console.log('enddate = ' + utils.dateFormat(date));
            let leaseDay = utils.diffDay(this.data.leaseDate,date);
            console.log("租借时长：" + leaseDay);
            if(leaseDay <= 0){
                formData.leaseDay = 1;
                this.setData({
                    revertDateStr:formData.leaseStartDate,
                    formData:formData
                })
                this._loadPriceInfo();
            }else if(leaseDay > 50){
                wx.showModal({
                    title: '温馨提示',
                    content: '租借天数不能超过50天',
                    showCancel:false
                })
                return;
            }else{
                formData.leaseDay = leaseDay;
                this.setData({
                    revertDateStr:utils.dateFormat(date),
                    formData:formData
                })
                this._loadPriceInfo();
            }
        }else if('appointmentTime' == key){
            formData.appointmentTime =  e.detail.value;
            this.setData({
                formData:formData
            })
        }
    },

    btnAgreementInfo:function(e){
        let key = e.currentTarget.dataset.key;
        if('RentAgreement' == key){
            //租凭服务协议
            this._loadAgreementInfo(key);
        }else if('PrivacyAgreement' == key){
            //隐私协议
            this._loadAgreementInfo(key);
        }
    },

    btnPriceList:function(e){
        this.setData({
            modalName:'priceList'
        })
    },

    btnPay:function(e){
        if(!this.data.isAgreement){
            wx.showModal({
                title: '温馨提示',
                content: '请阅读并同意《租凭服务协议》和《隐私协议》',
                showCancel:false
            })
            return;
        }
        
        let formData = this.data.formData;
        if(formData.leaseDay == 0){
            wx.showToast({title:'请选择租借时长',icon:'none'})
            return;
        }
        if(formData.leaseType == 3){
            if(addressInfo.id){
                buyData.addressId = addressInfo.id
            }else{
                wx.showToast({title:'请选择收货地址',icon:'none'})
                return;
            }
        }
        wx.showLoading({title: '支付中...'})
        api.post(api.url.bxscnBatteryPay,formData,res=>{
            if(res.data.code==200){
                const tradeNo = res.data.body.tradeNo;
                const payInfo = JSON.parse(res.data.body.payInfo);
                let count = 0;
                let timer = setInterval(()=>{
                    count++;
                    if(count>30){
                        clearInterval(timer);
                        timer = null;
                        wx.hideLoading();
                    }
                    api.post(api.url.bxscnBatteryPayResult,{
                        tradeNo:tradeNo,
                        payType:3
                    },res=>{
                        if(res.data.code == 200){
                            if(res.data.body.resultCode==2){
                                clearInterval(timer);
                                wx.hideLoading();
                                wx.showToast({
                                    title: '支付成功！',
                                    icon:'success',
                                    mask:true,
                                    success:()=>{
                                        setTimeout(() => {
                                            wx.reLaunch({url: `/pages/order/bxscn/shop/info?tradeNo=${tradeNo}`});
                                        }, 1000);
                                    }
                                })
                            }
                        }
                    })
                },1000)
                wx.requestPayment({
                    appId:payInfo.appId,
                    nonceStr: payInfo.nonceStr,
                    package: payInfo.package,
                    paySign: payInfo.sign,
                    timeStamp: payInfo.timeStamp+"",
                    signType:payInfo.signType,
                    success(){
                        console.log("===支付成功")
                        if(!timer){
                            wx.showToast({
                                title: '支付成功！',
                                icon:'success',
                                mask:true,
                                success:()=>{
                                    setTimeout(() => {
                                      wx.reLaunch({url: `/pages/order/bxscn/shop/info?tradeNo=${tradeNo}`});
                                    }, 1000);
                                }
                            })
                        }
                    },fail(err){
                        wx.hideLoading();
                        clearInterval(timer);
                        timer = null;
                        wx.showToast({
                            title: '支付失败',
                            icon:'error',
                            mask:true
                        })
                    }
                })
            }else if(res.data.msg){
                wx.hideLoading();
                wx.showModal({
                    content:res.data.msg,
                    showCancel:false
                })
            }else{
                wx.hideLoading();
                wx.showToast({
                  title:'预约失败',
                  icon:'error',
                  mask:true
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const _self = this;
        const eventChannel = this.getOpenerEventChannel();
        try{
            eventChannel.on('fromData', function(data) {
                console.log(data);
                let formData = _self.data.formData;
                let money = Number.parseFloat(data.info.depositMoney) + Number.parseFloat(data.info.dayMoney);
                formData.batteryType = data.info.id;
                formData.placeId = data.place.placeId;
                _self.setData({
                    info:Object.assign({},data.info),      //拷贝，避免该页面修改影响列表页面数据变更
                    place:Object.assign({},data.place),
                    formData:formData,
                    dayMoney:data.info.dayMoney,
                    money:money
                })
                _self._buildDate();
                _self._loadPriceInfo();
            })
        }catch (e) {
            wx.showToast({
              title: '参数错误',
              icon:'error'
            })
            setTimeout(() => {
                wx.navigateBack();
            }, 1000);
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})